<template>
  卡号：<input v-model="msg" />
  <hr />
  {{ msg }}
</template>
<script lang="ts">
import { customRef } from "vue";
export default {
  setup() {
    //带防抖功能的自定义响应式函数
    let myDebounceRef = function (value: any, delay: number) {
      let timer: number = 0;

      return customRef((track, trigger) => {
        return {
          get() {
            track(); //通知vue追踪该变量
            return value;
          },
          set(newValue) {
            if (timer) {
              //如果上一个时钟存在，则清除，重新计时
              clearTimeout(timer);
            }
            //延时赋值
            timer = setTimeout(() => {
              value = newValue;
              trigger(); //更新视图
              console.log("向服务器发送处理请求");
            }, delay);
          },
        };
      });
    };

    let msg = myDebounceRef("", 1000);
    return { msg };
  },
};
</script>
